app.controller('planCtrl', function($rootScope, $scope, httpService, $timeout, toaster, wtmapService, $parse,$localStorage){
    $scope.count=0;
    $scope.minDate = moment().startOf('month').format(wtSys.Emun.DateFormat.Date);
    $scope.maxDate = moment().endOf('month').format(wtSys.Emun.DateFormat.Date);
    $scope.queryParam = {
        Time : moment().format(wtSys.Emun.DateFormat.Date)
    }
    $scope.PlanStatus = wtSys.Emun.PlanStatus; //计划状态
    // $scope.PlanType = wtSys.Emun.PlanType; //计划类型
    // $scope.timeArr = wtSys.Emun.timeArr; //计划类型
    $scope.PlanTypes = wtSys.Emun.PlanTypes; //计划类型
    $scope.PlanSchedule = wtSys.Emun.PlanSchedule; //
    $scope.PlanTableData=[];//计划反馈
    $scope.searchList = [{
        "typeName" : "状态",
        "typeList" : [
            {"Id" : 0, "Name" : "未开始"},
            {"Id" : 1, "Name" : "进行中"},
            {"Id" : 2, "Name" : "已结束"},
        ],
    },];
    /**
     * 绘制定位点配置
     * @type {{layerid: string, 图层ID
     * symbolUrl: string 定位点图片Url }}
     */
    $scope.pointOption = {
        //layerid:图形图层id
        "layerid" : "locationLayer",
        "symbolUrl" : "/assets/img/gps_location.png"
    };
    //地图多点选择
    $scope.setLocationOption = {
        mapid : "setLocation",
        center : {x : 155307.451, y : 139762.144, lng : 0, lat : 0},
        zoom : 0,
        height : 600,
        showgdmap : false,
        layers : [
            //{layerName : "隐患点", layerFilter : ""},
            {layerName : "设备点", layerFilter : "unitid=" + $localStorage.userInfo.unitid}
        ]
    };

    /*==============设置选择设施位置信息 Begin=============================*/

    //设置选择设施位置信息
    $scope.isShowGetPosition = false;
    /**
     * 打开 选择设位置panel
     */
    $scope.openGetPositionPanel = function(){
        //$scope.isShowGetPosition = true;
        $scope.pointselectOption.initialayer = true; //初始化地图
        $('#deviceSelectModal').modal('show');
    }
    /**
     * 关闭 选择设位置panel
     */
    $scope.closeGetPositionPanel = function(){

        //开始赋值给modal
        var _results = $scope.pointselectOption.selecedresults;

        $scope.planModel.Places = _results.map(function(item){
            return item.attributes.id;
        });
        $scope.planModel.PlaceCodes = _results.map(function(item){
            return item.attributes.code;
        });
        $('#deviceSelectModal').modal('hide');
    }
    // 地图选择点配置信息
    $scope.pointselectOption = {
        //初始化图标
        toolItems : [
            //{ itemName: "Point", title: "点拾取", imgName: "D_点拾取.png"},
            {itemName : "Rectangle", title : "矩形拾取", imgName : "D_矩形拾取.png"},
            {itemName : "Polygon", title : "多边形拾取", imgName : "D_多边形拾取.png"}
        ],
        //展示底图图层
        pointLayers : [{
            lyrServerid : "1",
            layerName : "设备点",
            layerFilter : "unitid=" + $localStorage.userInfo.unitid,
            visibility : true,
            isDraw : false,
            featuresData : []
        }
            // { lyrServerid: "0", layerName: "隐患点", layerFilter: "", visibility:true, isDraw:false, featuresData: [] }
            //{ lyrServerid: "2", layerName: "隐患点", layerFilter: "",isDraw:true, requestUrl:"/danger?page=1&limit=100000", uniqueValues:{ valueField:"DangerStatus", renderInfos:renderInfo }, featuresData: [] }
        ],
        initialayer : false,
        //查询结果
        selecedresults : []
    }

    $scope.getPositionOption = {
        mapid : "getPosition",
        center : {x : 155307.451, y : 139762.144, lng : 0, lat : 0},
        zoom : 0,
        height : 600,
        showgdmap : false
    };
    //Edit状态默认被选中的点坐标
    $scope.selectedPosition = {x : 0, y : 0};
    /*==============设置选择设施位置信息 End=============================*/

    /*==============显示日记录 Begin=============================*/
    /**
     * 渲染日记录到table
     * @param tableClass
     * @param data 数据[[col1,col2]]
     */
    $scope.renderDailyData = function(tableClass, data){


        var $table = $("." + tableClass); // tr td成二维数组
        var _tdCount = $table.children("tr:eq(0)").children("td").length;
        /**
         * 生成多维数组
         * @param arr_description [2,3,4] 生成一个三维数组 arr = [[[1,2]*3]*4]
         * @param fillObj 填充obj一般用null
         * @returns {Array}
         * @private
         */
        var _createMultiArray = function(arr_description, fillObj){

            var arr = [];
            var fillObj = fillObj || null;

            if(arr_description && arr_description.length > 0){
                arr_description.forEach(function(item, index){
                    var _tempArr = [];//临时数组
                    for(var i = 0; i < item; i++){
                        if(index === 0){
                            _tempArr.push(fillObj);

                        } else {
                            _tempArr.push(arr);
                        }
                    }
                    arr = _tempArr;
                });

            } else {
                console.log(" arr_description 不是数组！");
            }

            return arr;

        };
        // reset table
        var tableData = _createMultiArray([2, 13, 10], null);
        if(_.isArray(tableData)){
            _.forEach(tableData, function(cols, rowIndex){

                _.forEach(cols, function(col, colIndex){
                    var _step = 2; //td步进值
                    var _tdIndex = colIndex;
                    _step = _step - (_tdCount - $table.children("tr:eq(" + _tdIndex + ")").children("td").length); //步进补偿，以防有td colspan
                    var _trIndex = rowIndex + _step;
                    /*if(col == "2"){
                     col = "✘";
                     } else if(col == "1"){
                     col = "✔";
                     }*/

                    var html_span_class = "none";
                    if(col && col[1] == 0){
                        html_span_class = "danger";
                    } else if(col && col[1] == 1){
                        html_span_class = "success";
                    }
                    var text = col[0] ? col[0] : "";
                    var html_span = '<span class="' + html_span_class + '" >' + text + '</span>';

                    $table.children("tr:eq(" + _tdIndex + ")").children("td:eq(" + _trIndex + ")").html(html_span);
                })

            });
        } else {
            return;
        }
        // init data
        if(_.isArray(data)){
            _.forEach(data, function(cols, rowIndex){

                _.forEach(cols, function(col, colIndex){
                    var _step = 2; //td步进值
                    var _tdIndex = colIndex;
                    _step = _step - (_tdCount - $table.children("tr:eq(" + _tdIndex + ")").children("td").length); //步进补偿，以防有td colspan
                    var _trIndex = rowIndex + _step;
                    /*if(col == "2"){
                     col = "✘";
                     } else if(col == "1"){
                     col = "✔";
                     }*/

                    var html_span_class = "none";
                    if(col && col[1] == 0){
                        html_span_class = "danger";
                    } else if(col && col[1] == 1){
                        html_span_class = "success";
                    }
                    var text = col[0] ? col[0] : "";
                    var html_span = '<span class="' + html_span_class + '" >' + text + '</span>';

                    $table.children("tr:eq(" + _tdIndex + ")").children("td:eq(" + _trIndex + ")").html(html_span);
                })

            });
        } else {
            return;
        }
    };
    // 查询计划反馈
    $scope.queryPlanFeed = function(){
        $scope.queryParam.queryTime = moment($scope.queryParam.Time).format(wtSys.Emun.DateFormat.Date);
        var path = '/feedback?filter=PlanId:'+$scope.activeId+';Date:'+$scope.queryParam.queryTime; // GET v2/inspection/daily?date={date}
        httpService.request("GET", path, null, function(result){
            if(result.success){
                var data=_.groupBy(result.data,'Name');
                var arr=[];
                _.forEach(data,function(value,key){
                    var Method=value.length>0?value[0].Method:null;
                    arr.push({
                        Name:key,
                        Method:Method,
                        valueArr:value,
                    })
                });
                $scope.PlanTableData=arr;
                // $scope.renderDailyData("data-daily", result.data);
            } else {
            }
        });

    };
    // 计划记录表格勾选情况
    $scope.isChecked=function(value){
        if(_.find($scope.PlanTableData,{Value:value})){
            return true
        }else{
            return false
        }
    };
    /*==============显示日记录 End=============================*/


    // 日期组件
    $scope.openDate = function($event, key){
        $event.preventDefault();
        $event.stopPropagation();
        if(key){
            $parse(key).assign($scope, true);
        }
    };
    // 初始化查询变量
    $scope.initParam = function(){
        $scope.planList = [];
        $scope.page = 1;
        $scope.busy = false;
        $scope.limit = 10;
        $scope.isGetDetailTag = true; //第一次默认加载第一条记录右侧信息
    }
    $scope.edit = function(item, index){
        // 还原表单以及表单值
        $scope.planForm.$setPristine();
        if(item && (item.Id || item.Id == 0)){
            if(item.PlanStatus == 1 || item.PlanStatus == 2){
                return;
            }
            $scope.planId = item.Id;
            $scope.index = index;
            $scope.editModalTitle = "修改周期计划";
            $scope.getPlanDetail($scope.planId);
        } else {
            $scope.planId = null;
            $scope.index = null;
            $scope.planModel = {
                // "PlanType": null,
                /*"No" : "",*/
                "Name" : "",
                "StartAt" : null,
                "EndAt" : null,
                "PlanType" : 1,
                "PlaceType" : 2, // 默认 2、点集合 1、片区
                "Interval" : 1,
                //"Items": [],
                "Places" : "",
                "Schedule" : $scope.PlanSchedule[0].Schedule,
                "Person" : "",
                "PersonType" : 3,
                "PersonName" : "",
                "Note" : ""
            };
            $scope.editModalTitle = "新增周期计划";
        }
        $('#editModal').modal('show');
    };
    //设施表单提交
    $scope.planFormSubmit = function(){
        $scope.planForm.$invalid = true;
        var path = "/plan";
        var type = "POST";
        if($scope.planId){
            path = "/plan/" + $scope.planId;
            type = "PUT";
        }
        /*$scope.planModel.Items=[{
         "StartAt":$scope.time.StartAt1,
         "EndAt":$scope.time.EndAt1,
         },{
         "StartAt":$scope.time.StartAt2,
         "EndAt":$scope.time.EndAt2,
         }];*/

        $scope.planModel.StartAt = moment($scope.planModel.StartAt).format(wtSys.Emun.DateFormat.Date);
        $scope.planModel.EndAt = moment($scope.planModel.EndAt).format(wtSys.Emun.DateFormat.Date);
        $scope.planModel.PersonName = _.result(_.find($scope.groupUserList, function(n){

            return n.Id == $scope.planModel.Person;
        }), 'Name');
        console.log($scope.planModel, $scope.groupUserList);
        httpService.request(type, path, $scope.planModel, function(result){
            $scope.planForm.$invalid = false;
            toaster.pop("success", "提示", result.message);
            $('#editModal').modal('hide');
            // 更新列表数据
            var arr = $scope.planList;
            if($scope.index != null && $scope.index >= 0){
                arr[$scope.index] = $scope.planModel; //index存在直接更新
                $scope.planDetailModel = angular.copy($scope.planModel); //更新右侧详情
            } else {
                arr.unshift(result.data);
                $scope.activeId = result.data.Id;
            }
            $scope.planList = arr;
        })
    }
    //删除设施弹框处理
    $scope.del = function(item, index){
        $scope.index = index;
        $scope.delModel = angular.copy(item);
        $('#delModal').modal('show');
    };
    //确认删除设施
    $scope.delConfirm = function(){
        $('#delModal').modal('hide');
        var path = '/plan/' + $scope.delModel.Id;
        httpService.request("DELETE", path, null, function(result){
            toaster.pop("success", "提示", result.message);
            // 更新列表数据
            var arr = $scope.planList;
            arr.splice($scope.index, 1);
            $scope.planList = arr;
            //如果删除的是第一条数据,删除成功后重新设置activeId的值
            if($scope.index == 0){
                $scope.activeId = arr[0] ? arr[0].Id : null;
            }
        });
    }
    //获取计划列表
    $scope.getPlanList = function(isSearch){
        if(isSearch){
            $scope.initParam();
        }
        if($scope.busy) return false;
        var key = $scope.key ? $scope.key : "";
        var planstatus = "";
        if($scope.searchModel){
            var arr = $scope.searchModel;
            if(arr.length > 0){
                var newArr = [];
                arr.forEach(function(item, index){
                    newArr.push(item.Id);
                });
                planstatus = newArr.join(",");
            }
        }
        var path = '/plan?page=' + $scope.page + '&limit=' + $scope.limit + '&filter=key:' + key + ";planstatus:" + planstatus;
        $scope.busy = true;
        httpService.request("GET", path, null, function(result){
            $scope.count=result.count;
            angular.forEach(result.data, function(data, i){
                $scope.planList.push(data);
            });
            if(result.data.length >= $scope.limit){
                $scope.busy = false;
                $scope.page += 1;
            }
            //搜索结果为空 将activeId置为空
            if($scope.planList.length==0){
                $scope.activeId=null;
                return
            }
            if($scope.planList.length > 0 && $scope.isGetDetailTag){
                $scope.isGetDetailTag = false;
                var arr = $scope.planList;
                $scope.activeId = arr[0].Id; //默认查询第一条记录的详情
            }
        });
    }
    //获取设施详情
    $scope.getPlanDetail = function(Id, isRgt){
        var path = '/plan/' + Id;
        httpService.request("GET", path, null, function(result){
            if(isRgt){
                $scope.planDetailModel = result.data;
                //1、改装下PlaceObj格式 给添加下x 和 y
                var _po = $scope.planDetailModel.PlacesObj;

                if(_po && _po.length > 0){
                    $scope.planDetailModel.PlacesObj =
                        $scope.planDetailModel.PlacesObj.map(function(item){
                            item.x = item.Lng;
                            item.y = item.Lat;
                            return item;
                        });
                }
            } else {
                $scope.planModel = result.data;
            }
        });
    }
    //获取右侧model
    $scope.getRgtModel = function(){
        //点击列表重置查询参数
        if(!$scope.activeId){
            return
        }
        $scope.getPlanDetail($scope.activeId, $rootScope.centerOptions); //获取设施详情
        $scope.queryPlanFeed();
    }
    //获取用户组列表
    $scope.getGroupUser = function(){
        var path = '/group?page=1&limit=10';
        httpService.request("GET", path, null, function(result){
            $scope.groupUserList = result.data;
        });
    }
    //下载表格
    $scope.downloadModal=function(){
        $('#downloadModal').modal('show');
    }
    $scope.downloadFormSubmit=function(){
        var begindate=moment($scope.downloadModel.begindate).format(wtSys.Emun.DateFormat.Date);
        var enddate=moment($scope.downloadModel.enddate).format(wtSys.Emun.DateFormat.Date);
        var path = CONFIG.basePathUrl+'/home/InspectionStandardExcel?id='+$scope.activeId+'&begindate='+begindate+'&enddate='+enddate;
        window.open(path);
    }
    //地图高度
    $scope.mapheight = ($(".rgt-wrap").height() - 85) || 700;

    $scope.mapService = wtmapService;
    // 地图初始化
    $scope.mapIntialed = function(scope){
        var promise = wtmapService.intialMap('map1', false, 0, $rootScope.arcgisConfig.lods); //同步调用，获取承诺接口

        promise.then(function(mapobj){
            mapobj.addDynamicMap($rootScope.arcgisConfig.baseMap);
            mapobj.addFeatureLayer("设备点", {
                maxScale : 0, minScale : 0, showInfoTemplate : false,
                definitionExpression : "unitid=" + $localStorage.userInfo.unitid
            });
            mapobj.zoomTobyXY(175307.451, 135762.144, 15);
            $scope.mapobj = mapobj;
            //获取计划列表
            $scope.getPlanList();
        }, function(data){
            //调用承诺接口reject();
        });

    };
    $scope.initParam(); // 初始化查询列表变量

    $scope.getGroupUser(); //获取用户组列表

    $scope.getPlanList();//获取计划列表
});
